
/*
 * 语音播报模块
 * 命令示例：
{
  "method": "set",
  "speech": "string"    string为需要播报的文本。编码方式必须为ANSI或者GB2312
  
  "method": "set",
  "set_speed": 1-10
  
  "method": "set",
  "set_intonation": 1-10
  
  "method": "set",
  "set_volume": 1-10
}
*/
#include "Arduino.h"    
#include <OneButton.h>       
#include <WiFi.h>
#include <SDDC_SDK_lib.h>
#include <cJSON.h>
#include <Wire.h>
//#include <Utf8ToUncode.h>
#include <XFS.h>



#define SDDC_CFG_PORT             680U             // SDDC 协议使用的端口号
#define PIN_INPUT                 0                // 选择 IO0 进行控制
#define ESP_TASK_STACK_SIZE       4096
#define ESP_TASK_PRIO             25

/*超时设置，示例为30S*/
static uint32_t LastSpeakTime = 0;
#define SpeakTimeOut 10000

static const char* ssid = "EOS-Tenda";             // WiFi 名
static const char* password = "1234567890";        // WiFi 密码
static double illu_val;
OneButton button(PIN_INPUT, true);
XFS5152CE xfs;

int UTF8ToUnicode (unsigned char *ch, int *unicode)  
{  
    unsigned char *p = NULL;  
    int e = 0, n = 0;  
    if (0 == (*ch & 0x80))
    {
          Serial.println("进入单字节判断");

        /*
         * single-byte char
         */
        unicode[0] = *ch;
    }
    else
    {
    if((p = ch) && unicode)  
    {  
        if(*p >= 0xfc)  
        {  
            /* 6:<11111100> */  
            e = (p[0] & 0x01) << 30;  
            e |= (p[1] & 0x3f) << 24;  
            e |= (p[2] & 0x3f) << 18;  
            e |= (p[3] & 0x3f) << 12;  
            e |= (p[4] & 0x3f) << 6;  
            e |= (p[5] & 0x3f);  
            n = 6;  
        }  
        else if(*p >= 0xf8)   
        {  
            /* 5:<11111000> */  
            e = (p[0] & 0x03) << 24;  
            e |= (p[1] & 0x3f) << 18;  
            e |= (p[2] & 0x3f) << 12;  
            e |= (p[3] & 0x3f) << 6;  
            e |= (p[4] & 0x3f);  
            n = 5;  
        }  
        else if(*p >= 0xf0)  
        {  
            /* 4:<11110000> */  
            e = (p[0] & 0x07) << 18;  
            e |= (p[1] & 0x3f) << 12;  
            e |= (p[2] & 0x3f) << 6;  
            e |= (p[3] & 0x3f);  
            n = 4;  
        }  
        else if(*p >= 0xe0)  
        {  
            /* 3:<11100000> */  
            e = (p[0] & 0x0f) << 12;  
            e |= (p[1] & 0x3f) << 6;  
            e |= (p[2] & 0x3f);  
            n = 3;  
        }  
        else if(*p >= 0xc0)   
        {  
            /* 2:<11000000> */  
            e = (p[0] & 0x1f) << 6;  
            e |= (p[1] & 0x3f);  
            n = 2;  
        }  
        else   
        {  
            e = p[0];  
            n = 1;  
        }  
        *unicode = e;  
    }
    }  
    /* Return bytes count of this utf-8 character */  
    return n;  
}  

int UTF8StrToUnicodeStr (unsigned char * utf8_str,  
                    unsigned short * unicode_str, int unicode_str_size)  
{  
    int unicode = 0;  
    int n = 0;  
    int count = 0;  
    unsigned char *s = NULL;  
    unsigned short *e = NULL;  
      
    s = utf8_str;  
    e = unicode_str;  
      
    if ((utf8_str) && (unicode_str))  
    {  
        while (*s)  
        {  
            if ((n = UTF8ToUnicode (s, &unicode)) > 0)  
            {  
                if ((count + 1) >= unicode_str_size)  
                {  
                    return count;  
                }  
                else  
                {  
                    *e = (unsigned short) unicode;  
                    e++;  
                    *e = 0;  
                      
                    /* Step to next utf-8 character */  
                    s += n;  
                }  
            }  
            else  
            {  
                /* Converting error occurs */  
                return count;  
            }  
        }  
    }  
      
    return count;  
} 

/*
 * 初始化语言播报模块函数
 */
static void XFS_Init()
{
    uint8_t n = 5;
    Serial.println("初始化语音播报模块");
    xfs.Begin(0x30);//设备i2c地址，地址为0x50
    delay(n);
    Serial.println("设置发音人");
    xfs.SetReader(XFS5152CE::Reader_XiaoYan);               //设置发音人
    delay(n);
    Serial.println("文本的编码格式");
    xfs.SetEncodingFormat(XFS5152CE::UNICODE);               //文本的编码格式
    delay(n);
    Serial.println("语种判断");
    xfs.SetLanguage(xfs.Language_Auto);                   //语种判断
    delay(n);
    Serial.println("合成风格设置");
    xfs.SetStyle(XFS5152CE::Style_Continue);              //合成风格设置
    delay(n);
    Serial.println("设置单词的发音方式");
    xfs.SetArticulation(XFS5152CE::Articulation_Letter);  //设置单词的发音方式
    delay(n);
    Serial.println("设置语速");
    xfs.SetSpeed(5);                                      //设置语速1~10
    delay(n);
    Serial.println("设置语调");
    xfs.SetIntonation(5);                                 //设置语调1~10
    delay(n);
    Serial.println("设置音量");
    xfs.SetVolume(10);                                     //设置音量1~10
    delay(n);
}

/*
 * 语音播报函数
 */
sddc_bool_t speech(const char* UTF8_str)
{
    unsigned short  unicode_str[31];
    printf("开始播报\n");
    printf("：UTF8_str %s\n",UTF8_str);
    if ((*UTF8_str & 0xf0) == 0xe0 )
    {
        UTF8StrToUnicodeStr((unsigned char*)UTF8_str, &unicode_str[0], 128);
        xfs.StartSynthesis((char *)unicode_str);
    }else {
        xfs.StartSynthesis((char *)UTF8_str);            // 选择播报的语句
    }
    
    while(xfs.GetChipStatus() != xfs.ChipStatus_Idle) //检查判断是否完成
    {
        delay(30);
    }
    return SDDC_TRUE;
}

/*
 * 设置语速函数
 */
sddc_bool_t SetSpeed(const uint64_t value)
{
   printf("设置语速\n");
   xfs.SetSpeed(value);
   return SDDC_TRUE;
}
/*
 * 设置语调函数
 */
sddc_bool_t SetIntonation(const uint64_t value)
{
   printf("设置语调\n");

    xfs.SetIntonation(value);
    return SDDC_TRUE;

}

/*
 * 设置音量函数
 */
sddc_bool_t SetVolume(const uint64_t value)
{
    xfs.SetVolume(value); 
    return SDDC_TRUE;
}
 
/* 
 *  数字量设备对象函数与处理方法注册
 */
NUM_DEV_REGINFO num_dev[] = {
//        {"set_num_demo", demo},                          // 字符串为输入命令，demo为命令处理函数
    {"SetSpeed",SetSpeed},
    {"SetIntonation",SetIntonation},
    {"SetVolume",SetVolume},
};

/*
 *  显示设备对象函数与处理方法注册
 */
DIS_DEV_REGINFO dis_dev[] = {
//        {"set_dis_demo", demo},                          // 字符串为输入命令，demo为命令处理函数
};

/*
 * IO设备对象设置函数与处理方法注册
 */
IO_DEV_REGINFO io_dev[] = {
//        {"set_io_demo", demo},                           // 字符串为输入命令，demo为命令处理函数
    {"speech",speech},
};

/*
 *  系统对象状态获取注册
 */
DEV_STATE_GET  dev_state_get_reg[] = {
//        {"demo",   DEV_NUM_TYPE,  num_get_demo},         // demo为输入命令，字符串为命令处理函数
//        {"demo",   DEV_IO_TYPE,  io_get_demo},
//        {"demo", DEV_DISPLAY_TYPE, dis_get_demo},
};

/*
 *  当前设备的信息定义
 */
DEV_INFO    dev_info = {
            .name     = "语音合成模块",
            .type     = "device.speech",
            .excl     = SDDC_FALSE,
            .desc     = "ESP-32S + 亚博语音合成播报模块",
            .model    = "IDSPEECHU01B",
            .vendor   = "inspiration-desktop",
};

/*
 *   系统注册对象汇聚
 */
SDDC_CONFIG_INFO sys_cfg = {
        .token             = "1234567890",            // 设备密码
        .devinfo           = &dev_info,               
        .io_dev_reg        = io_dev,
        .io_dev_reg_num    = ARRAY_SIZE(io_dev),
        .num_dev_reg       = num_dev,
        .num_dev_reg_num   = ARRAY_SIZE(num_dev),
        .state_get_reg     = dev_state_get_reg,
        .state_get_reg_num = ARRAY_SIZE(dev_state_get_reg),
        .dis_dev_reg       = dis_dev,
        .dis_dev_num       = ARRAY_SIZE(dis_dev),
};


/*
 * IO0 按键检测任务
 */
static void esp_io0_key_task()
{
    WiFi.disconnect();
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(1000);
        Serial.println("WIFI Wait for Smartconfig");
          
        // 设置为Station模式
        WiFi.mode(WIFI_STA);
          
        // 开始智能配网
        WiFi.beginSmartConfig();
        while (1)
        {
            delay(500);
            // 检查智能配网
            if (WiFi.smartConfigDone())
            {
                // 设置自动连接
                WiFi.setAutoConnect(true);  
                break;
            }
        }
    }
}

/*
 * 循环扫描按键
 */
static void esp_tick_task(void *arg)
{
    void *sddc = arg;
    (void)sddc;
    while(1)
    {
        button.tick();
        delay(100);
    }
}

/*
 * 初始化传感器
 */
void sensor_init()
{
    // 初始化语音播报模块
    XFS_Init();
}

void setup() {
    byte mac[6];
    Serial.begin(115200);
    Serial.setDebugOutput(true);
    Serial.println();

    // 初始化传感器
    sensor_init();

    // 清除一下按键状态机的状态
    button.reset();
  
    // 创建按键扫描线程，长按 IO0 按键，松开后ESP32 将会进入 SmartConfig 模式
    sddc_printf("长按按键进入 Smartconfig...\n");
    button.attachLongPressStop(esp_io0_key_task);
    xTaskCreate(esp_tick_task, "button_tick", ESP_TASK_STACK_SIZE, NULL, ESP_TASK_PRIO, NULL);

    // 启动 WiFi 并且连接网络
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) 
    {
        delay(500);
        Serial.print(".");
    }
    
    // 获取并打印 IP 地址
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.print("'ip :");
    Serial.print(WiFi.localIP());
    Serial.println("' to connect"); 

    // sddc协议初始化
    sddc_lib_main(&sys_cfg);

    // 获取并打印网卡 mac 地址
    WiFi.macAddress(mac);
    sddc_printf("MAC addr: %02x:%02x:%02x:%02x:%02x:%02x\n",
              mac[5], mac[4], mac[3], mac[2], mac[1], mac[0]);
    // 使用网卡 mac 地址设置设备唯一标识 UID
    sddc_set_uid(G_sddc, mac);
}

void loop() {
    // 运行 SDDC 协议循环
    while (1) 
    {
        sddc_printf("SDDC running...\n");
        sddc_run(G_sddc);
        sddc_printf("SDDC quit!\n");
    }

    // 销毁 SDDC 协议
    sddc_destroy(G_sddc);
}
